package org.intrasearch.core;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.*;

public abstract class ResourceArtifactBase<T extends ResourceArtifact> implements ResourceArtifact<T>, Externalizable
{
    protected SortedSet<String> urls;
    protected String name;
    protected ArtifactId artifactId;

    protected ResourceArtifactBase(Set<String> urls, String name)
    {
        this.urls = createUrlsSet(urls);
        this.name = name;
    }

    protected ResourceArtifactBase()
    {
    }

    protected abstract ArtifactId generateArtifactId();

    protected SortedSet<String> createUrlsSet(Set<String> urls)
    {
        TreeSet<String> urlTreeSet = createUrlSet();
        urlTreeSet.addAll(urls);
        return urlTreeSet;
    }

    private TreeSet<String> createUrlSet()
    {
        return new TreeSet<String>();
    }

    public ArtifactId getArtifactId()
    {
        if (artifactId == null)
        {
            artifactId = generateArtifactId();
        }
        return artifactId;
    }

    public List<String> getUrls()
    {
        return new ArrayList<String>(urls);
    }

    public String getName()
    {
        return name;
    }

    protected void writeUrls(ObjectOutput out)
            throws IOException
    {
        out.writeInt(urls.size());
        for (String url : urls)
        {
            out.writeUTF(url);
        }
    }

    protected void readUrls(ObjectInput in)
            throws IOException
    {
        urls = createUrlSet();
        int size = in.readInt();
        for (int i = 0; i < size; i++)
        {
            urls.add(in.readUTF());
        }
    }

    public void writeExternal(ObjectOutput out) throws IOException
    {
        out.writeUTF(name);
        writeUrls(out);
    }

    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
    {
        name = in.readUTF();
        readUrls(in);
    }

    protected SortedSet<String> mergeUrls(ResourceArtifact<T> nextArtifact)
    {
        SortedSet<String> urlHashSet = createUrlsSet(urls);
        urlHashSet.addAll(nextArtifact.getUrls());
        return urlHashSet;
    }
}
